//
//  UIColor+Create.m
//  GuChat
//
//  Created by iBenz on 15/6/1.
//  Copyright (c) 2015年 Guzhi Tech. All rights reserved.
//

#import "UIColor+Create.h"

@implementation UIColor(Create)

+ (UIColor *)colorWithHexString:(NSString *)hexValue {
    NSString *hexPrefix = @"0x";
    hexValue = [hexValue lowercaseString];
    if ([hexValue hasPrefix:@"#"]) {
        hexValue = [hexValue stringByReplacingOccurrencesOfString:@"#" withString:hexPrefix];
    }
    if (![hexValue hasPrefix:hexPrefix]) {
        hexValue = [hexPrefix stringByAppendingString:hexValue];
    }
    
    unsigned alpha = 255.0;
    if (hexValue.length==10) {
        // with alpha value
        NSString *alphaStr = [hexValue substringFromIndex:8];
        [[NSScanner scannerWithString:[@"0x" stringByAppendingString:alphaStr]] scanHexInt:&alpha];
        hexValue = [hexValue substringToIndex:8];
    }
    return [UIColor colorWithHexString:hexValue alpha:alpha/255.0];
}

+ (UIColor *)colorWithHexString:(NSString *)hexValue alpha:(CGFloat)alpha {
    if (hexValue.length<6) {
        return [UIColor clearColor];
    }
    
    NSString *hexPrefix = @"0x";
    hexValue = [hexValue lowercaseString];
    if ([hexValue hasPrefix:@"#"]) {
        hexValue = [hexValue stringByReplacingOccurrencesOfString:@"#" withString:hexPrefix];
    }
    if (![hexValue hasPrefix:hexPrefix]) {
        hexValue = [hexPrefix stringByAppendingString:hexValue];
    }
    
    if (hexValue.length==10) {
        hexValue = [hexValue substringToIndex:8];
    }
    
    if (hexValue.length!=8) {
        return [UIColor clearColor];
    }
    
    unsigned long long value;
    [[NSScanner scannerWithString:hexValue] scanHexLongLong:&value];
    return [UIColor colorWithHexValue:value alpha:alpha];
}

+ (UIColor *)colorWithHexValue:(unsigned long long)rgbValue {
    return [UIColor colorWithHexValue:rgbValue alpha:1.0];
}

+ (UIColor *)colorWithHexValue:(unsigned long long)rgbValue alpha:(CGFloat)alpha {
    return [UIColor colorWithRed : ((float)((rgbValue & 0xFF0000) >> 16)) / 255.0 green : ((float)((rgbValue & 0xFF00) >> 8)) / 255.0 blue : ((float)(rgbValue & 0xFF)) / 255.0 alpha : alpha];
}

+ (HexBlock)hexColor {
    return ^UIColor *(unsigned long long hexValue){
        return UIColor.hexAlphaColor(hexValue, 1.0);
    };
}
+ (HexAlphaBlock)hexAlphaColor {
    return ^UIColor* (unsigned long long hexValue, CGFloat alpha) {
        return [UIColor colorWithRed : ((float)((hexValue & 0xFF0000) >> 16)) / 255.0 green : ((float)((hexValue & 0xFF00) >> 8)) / 255.0 blue : ((float)(hexValue & 0xFF)) / 255.0 alpha : alpha];
    };
}

@end

UIColor *HexColor(unsigned long long hexValue) {
    return UIColor.hexColor(hexValue);
}

UIColor *HexAlphaColor(unsigned long long hexValue, CGFloat alpha) {
    return UIColor.hexAlphaColor(hexValue, alpha);
}
